<?php
// +----------------------------------------------------------------------
// | 分销联盟数据处理
// +----------------------------------------------------------------------
// | Author: TongBC <50249101@qq.com>
// +----------------------------------------------------------------------
// | Date  : 2015/03/06
// +----------------------------------------------------------------------
include("/var/www/html/new/com.inc.php");
include('/var/www/html/new/d/common/autoload.php');
include('/var/www/html/new/d/class/MemberAccount.class.php');
include('/var/www/html/new/d/class/Alliance.class.php');
include('/var/www/html/new/d/class/Member.php');
include('/var/www/html/new/d/class/abc/Syslog.class.php');
include('/var/www/html/new/d/class/abc/Member.class.php');


$ac=$GLOBALS['_ac'];
$pw=$GLOBALS['_pw'];
$s = new SoapClient(null,array("location" => "http://localhost/open/openService/pft_insideMX.php","uri" => "www.16u.com?ac_16u=$ac|pw_16u=$pw|auth_16u=true"));

$action = trim($_REQUEST['action']);
if($action=='register'){
    if($_SESSION['sid']!=1) exit('{"status":"fail","mesg":"非法访问"}');
}


switch($action) {
	
	// 会员提交申请进入联盟
	case 'apply_union':

		// 1.基本情况判断
		$aid = $_POST['aid'] + 0;// 联盟ID
		$mid = $_SESSION['sid']; // 会员ID
		
		// 申请身份
		$identity = 0; // 1 供销商 2 供应商 3 分销商
		if(isset($_REQUEST['us']) && $_REQUEST['us']==1) $identity=2;
		if(isset($_REQUEST['ud']) && $_REQUEST['ud']==1) $identity=3;
		if(isset($_REQUEST['ud']) && isset($_REQUEST['us'])) $identity=1;
		if($identity==0) exit('{"status":"fail","mesg":"请选择申请加入的联盟身份"}');
		
		
		if($aid==0) exit('{"status":"fail","msg":"参数错误"}');// 没传递联盟ID参数
		
		if($_REQUEST['pto']!='1') exit('{"status":"fail","msg":"请先阅读协议并同意"}');
		
		$sql = "select id,fid,cash_pledge from `pft_distributor_union_SE` where id=$aid limit 1";
		$GLOBALS['le']->query($sql);
		if(!$GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","mesg":"联盟不存在"}');
		
		$deposit = $GLOBALS['le']->f('cash_pledge');// 
		$fid = $GLOBALS['le']->f('fid');
		
		if($sid==$fid) exit('{"status":"fail","mesg":"自己不允许加入自己创建的联盟"}');

		// 是否资质认证
		$sql = "select certi_status from pft_member_extinfo where fid=$mid limit 1";
		$GLOBALS['le']->query($sql);
		if(!$GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","mesg":"账号信息出错"}');
		if($GLOBALS['le']->f('certi_status')!=2) exit('{"status":"fail","mesg":"您未通过资质认证","code":101}');
		
		// 是否已申请   类型|押金|状态   0 未交 1 已交
		$deposit_a = explode('|', $deposit);
		$dmoney = $deposit_a[($identity-1)];// 需缴纳押金
//		$roleDt = $identity.'|'.$dmoney.'|0';
        $roleDt = $identity.'|0|0';
		
		$union_id = 0;
		$sql = "select id,dstatus,role_pledge from pft_union_member_info_SE where fid=$fid and memberID=$mid limit 1";
		$GLOBALS['le']->query($sql);
		if($GLOBALS['le']->fetch_assoc()){
			$dstatus  = $GLOBALS['le']->f('dstatus');
			$union_id = $GLOBALS['le']->f('id');
			if($dstatus== '0') exit('{"status":"fail","mesg":"您已通过审核，请勿重复提交"}');
			if($dstatus== '2') exit('{"status":"fail","mesg":"您的申请已递交，请勿重复申请"}');
			// if($dstatus==4) exit('{"status":"fail","mesg":"您已被禁止加入该联盟，请联系联盟发起人"}');
			$deposit_arr = explode('|', $GLOBALS['le']->f('role_pledge'));
			if($deposit_arr[2]==1) exit('{"status":"fail","mesg":"盟主未退还押金，请先联系盟主退还押金后申请"}');
		}

		if($union_id==0){
			$sql = "insert into  pft_union_member_info_SE set dstatus=2,role_pledge='$roleDt',fid=$fid,memberID=$mid,jointime=now()";
			if($GLOBALS['le']->query($sql)) exit('{"status":"success","mesg":"申请成功"}');
			exit('{"status":"fail","mesg":"申请失败"}');
		}

		$sql = "update pft_union_member_info_SE set dstatus=2,role_pledge='$roleDt' where id=$union_id and fid=$fid limit 1";
		if($GLOBALS['le']->query($sql)) exit('{"status":"success","mesg":"申请成功"}');
		exit('{"status":"fail","mesg":"申请失败"}');
		break;
		
	// 审核操作
	case 'audit_do':
		$fid   = $_SESSION['sid'] + 0;        // 联盟盟主ID
		$mid   = $_REQUEST['mid'] + 0;        // 会员ID
		$msg   = $_REQUEST['msg'];            // 驳回消息
		$state = $_REQUEST['status'] + 0;     // 审核状态

        audit_do:
		$sql = "select id,dstatus,role_pledge from pft_union_member_info_SE where fid=$fid and memberID=$mid order by id desc limit 1";
		$GLOBALS['le']->query($sql);
		if(!$GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","msg":"记录不存在"}');
		
		$roleDt   = $GLOBALS['le']->f('role_pledge');
		$dstatus  = $GLOBALS['le']->f('dstatus');
		$union_id = $GLOBALS['le']->f('id');
		$deposit  = explode('|', $roleDt);
		$dmoney   = $deposit[1];// 退还押金金额
		
		
		if($state==1 || $state==3){// 驳回与退出
		
			if($state==1){
				
				// 断连供应商分销商关系
				$mem = new pft\Member\MemberAccount($GLOBALS['le']);
				if($deposit[0]==1 || $deposit[0]==2) $mem->RelationHanler(pft\Member\MemberAccount::RELATION_REMOVE, $fid, $mid);
				if($deposit[0]==1 || $deposit[0]==3) $mem->RelationHanler(pft\Member\MemberAccount::RELATION_REMOVE, $mid, $fid);
				$sql = "update pft_union_member_info_SE set dstatus=1,ref_reason='' where
                        id=$union_id limit 1";
				if($GLOBALS['le']->query($sql)) exit('{"status":"success","msg":"退出成功"}');
				exit('{"status":"fail","msg":"退出失败"}');
			}else{
				$sql = "update pft_union_member_info_SE set dstatus=3,ref_reason='$msg' where id=$union_id and memberID=$mid limit 1";
				if($GLOBALS['le']->query($sql)) exit('{"status":"success","msg":"驳回成功"}');
				exit('{"status":"fail","msg":"驳回失败"}');
			}
			
		}else{
			if($dstatus!=2) exit('{"status":"fail","msg":"不存在需要审核的记录"}');
			
			$mem = new pft\Member\MemberAccount($GLOBALS['le']);
			// 根据不同角色设置产品权限 1 供销商 2 供应商 3 分销商			
			if($deposit[0]==1 || $deposit[0]==2){
				abc777\Member::RelationShip($mid, $fid);
				// abc777\Syslog::write_log("abc777\MemberRelationShip($mid, $fid)","aaa_a");
			}
			if($deposit[0]==1 || $deposit[0]==3){
				
				abc777\Member::RelationShip($fid, $mid);
				// abc777\Syslog::write_log("abc777\MemberRelationShip($fid, $mid)","aaa_a");
				
				// 更改状态
				$sql = "update pft_union_member_info_SE set dstatus=0 where id=$union_id and memberID=$mid limit 1";
				if(!$GLOBALS['le']->query($sql)) exit('{"status":"success","msg":"审核失败"}');
				
				// 自己供应产品的购买产品
				$upd = "update `pft_product_sale_list` set `status`=0,`pids`='A' where aid=$fid and fid=$mid limit 1";
				$GLOBALS['le']->query($upd);
				
				// 3.2配置转分销产品购买权限
				$sql="select * from `pft_p_apply_evolute` where fid=$fid and status=0 and active=1 and sourceid<>$mid and sid<>$mid";
				$GLOBALS['le']->query($sql);
				while($row = $GLOBALS['le']->fetch_assoc()){
					// 供应链存在该分销商
					if(in_array($mid, explode(',', $row['aids']))) continue;
					$evolute[$row['pid']] = array(
						'aids'=>$row['aids'],
						'pid'=>$row['pid'],
						'sid'=>$row['sid'],
						'sourceid'=>$row['sourceid'],
						'lvl'=>$row['lvl'],
					);
				}
				
				$sets = array();// 获取已经设置的记录
				$sql = "select pid,status,id from `pft_p_apply_evolute` where sid=$fid and fid=$mid";
				$GLOBALS['le']->query($sql);
				while($row = $GLOBALS['le']->fetch_assoc()){
					$sets[$row['pid']] = $row;
				}
				
				// 3.3为分销商设置自己可购买转分销产品
				$ins_f = false; $upd_a = array();
				if(count($evolute)){
					$ins = "insert into `pft_p_apply_evolute` (fid,sid,aids,sourceid,pid,lvl,rectime) values ";
					foreach($evolute as $pid=>$data){
						if(isset($sets[$pid])){
							if($sets[$pid]['status']==1){
								$upd_a[] = $sets[$pid]['id'];
							} 
							continue;
						}
						// 没有配置，新增
						$lvl = $data['lvl'] + 1;
						$aids = $data['aids'].','.$fid;
						$ins.="($mid,$fid,'$aids',{$data['sourceid']},$pid,$lvl,now()),";
						$ins_f = true;
					}
					if($ins_f) $GLOBALS['le']->query(rtrim($ins, ','));
				}
				
				if(($size = count($upd_a))){
					$ids = implode(',', $upd_a);
					$upd = "update pft_p_apply_evolute set status=0 where id in ($ids) limit $size";
					$GLOBALS['le']->query($upd);
				}
			}
			
		}
		exit('{"status":"success","msg":"加入成功"}');
		break;
    //显示加入了哪些联盟 状态如何 union.html
    case'show_alliance':
        $sql = "select fid,dstatus,role_pledge from pft_union_member_info_SE where memberID={$_SESSION['sid']} and dstatus<>1";
        $GLOBALS['le']->query($sql);
        while($row=$GLOBALS['le']->fetch_assoc()){
            $role_pledge = explode('|',$row['role_pledge']);
            switch ($row['dstatus']) {
            	case '0':
                    $row['dstatus'] = '正常';
            		break;
                case '1':
                    $row['dstatus'] = '退出';
                    break;
                case '2':
                    $row['dstatus'] = '已申请';
                    break;
                case '3':
                    $row['dstatus'] = '驳回';
                    break;
            }
            $r[] = array(
                'fid'     =>$row['fid'],
                'dstatus' =>$row['dstatus'],//状态
                'ya_money'=>$role_pledge[1] ? ($role_pledge[1])/100: 0 ,//押金
                'ya_status'=>$role_pledge[2] ? $role_pledge[2] : 0,//是否已交押金
            );
        }
        if(count($r)){
            foreach($r as $k => $v){
                $sql = "select dtitle from pft_distributor_union_SE where fid={$v['fid']} limit 1";
                $GLOBALS['le']->query($sql);
                $GLOBALS['le']->fetch_assoc();
                $dtitle = $GLOBALS['le']->f('dtitle');
                $r[$k]['dtitle'] = $dtitle;
            }
        }
        $sta = $r ?'suc' : 'fail';
        exit(json_encode(
            array(
                'sta'=>$sta,
                'list'=>$r
            )
        ));
        break;
    //会员退出 union.html
    case 'union_quite':
        $fid   = $_POST['fid'] + 0;        // 联盟盟主ID
        $mid   = $_SESSION['sid'] + 0;        // 会员ID
        $state = $_POST['status'] + 0;

        goto audit_do;
        break;

    //交押金的弹框里的数据 union.html
    case 'alert_box_pledge':
        include_once("../class/Member.php");
        $m=new Member($s,$_SESSION['sid']);
        $money=$m->money()/100;

        $fid = $_POST['fid']+0;

        $sql = "select cash_pledge from pft_distributor_union_SE where fid=$fid limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $cash_pledge = $GLOBALS['le']->f('cash_pledge');
        $cash_pledge = explode('|',$cash_pledge);

        $sql = "select role_pledge from pft_union_member_info_SE where
         memberID={$_SESSION ['sid']} and fid=$fid limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $role_pledge = $GLOBALS['le']->f('role_pledge');
        $role_pledge = explode('|',$role_pledge);
        $ya_money = ($cash_pledge[$role_pledge[0]-1])/100;

        $enough_money = (float)$money-(float)$ya_money >= 0 ? '1' : '0';
        exit('{
            "sta":"suc",
            "local_money":"'.$money.'",
            "enough_money":'.$enough_money.',
            "ya_money":"'.$ya_money.'"
        }');
        break;
    //处理交押金的数据 union.html
    case 'hand_in_pledge':
        $fid = $_POST['fid']+0;
        $sql = "select role_pledge from pft_union_member_info_SE where
         memberID={$_SESSION ['sid']} and fid=$fid limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $role_pledge = $GLOBALS['le']->f('role_pledge');
        $role_pledge = explode('|',$role_pledge);
        if($role_pledge[2] == 1)
            exit('{"sta":"fail","msg":"已经交过押金了"}');
        include_once("../class/Member.php");
        $m=new Member($s,$_SESSION['sid']);
        $money=$m->money();

        $sql = "select cash_pledge,dtitle from pft_distributor_union_SE where fid=$fid limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $cash_pledge = $GLOBALS['le']->f('cash_pledge');
        $cash_pledge = explode('|',$cash_pledge);
        $ya_money = ($cash_pledge[$role_pledge[0]-1]);

        if((float)$money<(float)$ya_money)
            exit('{"sta":"fail","msg":"你的账户余额不足"}');
        $union_name = $GLOBALS['le']->f('dtitle');
        //盟主加钱
        if($s->PFT_Member_Fund_Modify($fid,$fid,$ya_money,0,0,null,15,0,null,'联盟内会员['.$_SESSION['dname'].']支付押金')){
            //会员扣钱
            if($s->PFT_Member_Fund_Modify($_SESSION['sid'],$_SESSION['sid'],$ya_money,1,0,null,15,0,null,'加入['.$union_name.']联盟的押金')){
                $role_pledge = (string)$role_pledge[0].'|'.(string)$ya_money.'|1';
                $sql = "update pft_union_member_info_SE set role_pledge='$role_pledge' where memberID={$_SESSION ['sid']} and fid=$fid limit 1";
                if($GLOBALS['le']->query($sql))
                    exit('{"sta":"suc","msg":"已成功支付押金"}');
                else{
                    $s->PFT_Member_Fund_Modify($_SESSION['sid'],$_SESSION['sid'],$ya_money,0,0,null,15,0,null,'支付给['.$union_name.']联盟的押金失败,返回资金');
                    $s->PFT_Member_Fund_Modify($fid,$fid,$ya_money,1,0,null,15,0,null,'联盟内会员['.$_SESSION['dname'].'支付押金失败,回扣资金');
                    write_logs('修改联盟会员表pft_union_member_info_SE押金支付记录role_pledge失败,语句:'.$sql);
                    exit('{"sta":"fail","msg":"支付押金失败"}');
                }
            }else{
                $s->PFT_Member_Fund_Modify($fid,$fid,$ya_money,1,0,null,15,0,null,'联盟内会员['.$_SESSION['dname'].'支付押金失败,回扣资金');
                write_logs('会员支付押金失败,fid:'.$_SESSION['sid'].',ya_money:'.$yamoney);
                exit('{"sta":"fail","msg":"支付押金失败"}');
            }
        }else{
            write_logs('盟主收入押金失败,fid:'.$fid.',ya_money:'.$yamoney);
            exit('{"sta":"fail","msg":"支付押金失败"}');
        }
    //盟主给会员退押金 alliance_mem.html
    case 'hand_out_pledge' :
        $mid = $_REQUEST['mid'] + 0;        // 会员ID
        $sql = "select role_pledge from pft_union_member_info_SE where
                memberID=$mid and fid={$_SESSION['sid']} limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $role_pledge = $GLOBALS['le']->f('role_pledge');
        $role_pledge_new = explode('|',$role_pledge);
        if($role_pledge_new[2]!=1){
            exit('{"sta":"fail","msg":"该会员尚未交押金或已退押金"}');
        }
        $ya_money = $role_pledge_new[1];
        $sql = "select dname from pft_member where id=$mid limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $dname = $GLOBALS['le']->f('dname');
        //盟主扣钱
        if($s->PFT_Member_Fund_Modify($_SESSION['sid'],$_SESSION['sid'],$ya_money,1,0,null,15,0,null,'退还给前会员['.$dname.']押金')){
            //会员加钱
            if($s->PFT_Member_Fund_Modify($mid,$mid,$ya_money,0,0,null,15,0,null,'['.$_SESSION['dname'].']联盟退还押金')){
                $role_pledge = $role_pledge_new[0].'|0|0';
                $sql = "update pft_union_member_info_SE set role_pledge=$role_pledge where
                        memberID=$mid and fid={$_SESSION['sid']} limit 1";
                if($GLOBALS['le']->query($sql)){
                    exit('{"sta":"suc","msg":"已成功退还押金"}');
                }else{
                    $s->PFT_Member_Fund_Modify($mid,$mid,$ya_money,1,0,null,15,0,null,'['.$_SESSION['dname'].']联盟退还押金失败,扣除资金');
                    $s->PFT_Member_Fund_Modify($_SESSION['sid'],$_SESSION['sid'],$ya_money,0,0,null,15,0,null,'退还给前会员['.$dname.']押金失败,返回资金');
                    write_logs('修改联盟会员表pft_union_member_info_SE押金支付记录role_pledge失败,语句:'.$sql);
                    exit('{"sta":"fail","msg":"退还押金失败"}');
                }
            }else{
                $s->PFT_Member_Fund_Modify($_SESSION['sid'],$_SESSION['sid'],$ya_money,0,0,null,15,0,null,'退还给前会员['.$dname.']押金失败 返回资金');
                write_logs('会员收入联盟退还的押金失败,fid:'.$mid.',ya_money:'.$yamoney);
                exit('{"sta":"fail","msg":"退还押金失败"}');
            }
        }else{
            write_logs('盟主退还押金失败,fid:'.$_SESSION['sid'].',ya_money:'.$yamoney);
            exit('{"sta":"fail","msg":"退还押金失败"}');
        }
        break;
    default:break;
}

function write_logs($txt,$file='/var/www/html/new/d/logs/union_ya_money.log'){
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

